package com.demo.service.config;

import com.demo.service.properties.MqttProperties;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Mqtt客户端连接对象
 */
@Component
public class MqttClientConnection {

    //从配置文件中获取配置
    @Autowired
    private MqttProperties mqttProperties;
    //发布主题客户端
    public static MqttClient publishmqttClient;
    //订阅主题客户端
    public static MqttClient subscribemqttClient;

    /**
     * 获取发布客户端
     *
     * @return
     */
    public MqttClient getPublishClient() {
        try {
            publishmqttClient = new MqttClient(mqttProperties.getBroker(), mqttProperties.getPublishClientId(), new MemoryPersistence());

        } catch (MqttException e) {
            e.printStackTrace();
        }
        return publishmqttClient;

    }

    /**
     * 获取订阅客户端
     *
     * @return
     */
    public MqttClient getSubscribemqttClient() {

        try {
            subscribemqttClient = new MqttClient(mqttProperties.getBroker(), mqttProperties.getSubscribeClientId(), new MemoryPersistence());

        } catch (MqttException e) {
            e.printStackTrace();
        }
        return subscribemqttClient;
    }

    /**
     * mtqq连接配置
     *
     * @return
     */
    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        //创建连接配置
        MqttConnectOptions ConnectOptions = new MqttConnectOptions();
        //设置账户名称
        ConnectOptions.setUserName(mqttProperties.getUsername());
        //设置账户密码
        ConnectOptions.setPassword(mqttProperties.getPassword().toCharArray());
        // 设置超时时间
        ConnectOptions.setConnectionTimeout(60);
        // 设置会话心跳时间
        ConnectOptions.setKeepAliveInterval(60);
        /*
         * 设置如果连接断开，客户端是否将自动尝试重新连接到服务器。
         * 如果设置为false，则在连接丢失的情况下，客户端将不会尝试自动重新连接到服务器。
         * 如果设置为true，则在连接断开的情况下，客户端将尝试重新连接到服务器。
         * 它最初会等待1秒它会尝试重新连接之前，对于每一个失败的尝试重新连接，延迟将增加一倍，直到它于2分钟，
         * 此时的延迟将保持在2分钟。
         * 参数：
         * automaticReconnect-如果设置为True，将启用自动重新连接
         */
        ConnectOptions.setAutomaticReconnect(true);
        // 是否清除session
        ConnectOptions.setCleanSession(true);
        return ConnectOptions;
    }


}
